package com.group.a;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Hello world!
 */
public class FileChlDemo {
    private static final String PATH = "H:/file-channel.txt";
    private static final String UTF8 = "UTF-8";


    public static void main(String[] args) {
        try {
            writeFile("hello,world!");
            String text = readFile(PATH);
            System.out.println(text);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String readFile(String filePath) throws IOException {
        Path path = Paths.get(filePath);
        FileChannel fc = FileChannel.open(path);
        ByteBuffer byteBuffer = ByteBuffer.allocate((int) (fc.size() + 1));
        fc.read(byteBuffer);
        byteBuffer.flip();

        Charset charset = Charset.forName(UTF8);
        CharBuffer charBuffer = charset.decode(byteBuffer);
        return new String(charBuffer.array());
    }

    private static void writeFile(String text) throws IOException {
        File file = new File(PATH);
        if (!file.exists()){
            file.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(file);
        FileChannel fc = fos.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(64);
        byteBuffer.put(text.getBytes(UTF8));
        byteBuffer.flip();
        fc.write(byteBuffer);

        fc.close();
        fos.close();
    }
}
